<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'">
  </head>
  <body>
    <script>
      const DATABASE_NAME = 'p4-local-settings';
      const DATABASE_VERSION = 1;
      const STORE_NAME = 'blobs';

      let blobItemsToImport = [];
      let blobDatabase = null;

      const openBlobsDatabase = () => new Promise((resolve, reject) => {
        const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
        request.onerror = () => {
          reject(new Error(`Failed to open: ${request.error}`));
        };
        request.onupgradeneeded = (e) => {
          const db = e.target.result;
          db.createObjectStore(STORE_NAME, {
            keyPath: 'id'
          });
        };
        request.onsuccess = () => {
          resolve(request.result);
        };
      });

      const putInDatabase = (database, data) => new Promise((resolve, reject) => {
        const transaction = database.transaction(STORE_NAME, 'readwrite');
        transaction.onerror = () => {
          reject(new Error(`Transaction error: ${transaction.error}`));
        };

        const objectStore = transaction.objectStore(STORE_NAME);
        const request = objectStore.put(data);
        request.onsuccess = () => {
          resolve();
        };
      });

      const PARENT_ORIGIN = 'file://';

      window.addEventListener('message', async (e) => {
        try {
          if (e.origin !== PARENT_ORIGIN) {
            return;
          }

          const data = e.data;

          if (data.storage) {
            for (const [key, value] of Object.entries(data.storage)) {
              localStorage[key] = value;
            }
          }

          if (data.blobKeys) {
            if (data.blobKeys.length > 0) {
              blobItemsToImport = data.blobKeys;
              blobDatabase = await openBlobsDatabase();
            }
          }

          if (data.blobData) {
            await putInDatabase(blobDatabase, data.blobData);
            await new Promise((resolve, reject) => setTimeout(resolve, 1000 / 60));
          }

          // We've gathered all the data from the request, so see if we need to ask
          // for anything more.
          if (blobItemsToImport.length > 0) {
            const key = blobItemsToImport.shift();
            e.source.postMessage({
              type: 'blob',
              key: key
            }, PARENT_ORIGIN);
          } else {
            // We're done
            e.source.postMessage({
              type: 'done'
            }, PARENT_ORIGIN);
          }
        } catch (error) {
          console.error(error);
          e.source.postMessage({
            type: 'error',
            error: `${error}`
          }, PARENT_ORIGIN);
        }
      });

      window.parent.postMessage({
        type: 'start'
      }, PARENT_ORIGIN);
    </script>
  </body>
</html>
